package com.snap.awesomeserial.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;

import com.snap.awesomeserial.AppConfig;
import com.snap.awesomeserial.R;
import com.snap.awesomeserial.base.BaseActivity;
import com.snap.awesomeserial.bean.SerialPortDevice;
import com.snap.awesomeserial.serial.Cmd;
import com.snap.awesomeserial.serial.SerialPortHelper;
import com.snap.awesomeserial.utils.ToastUtils;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.BindView;

public class MainActivity extends BaseActivity {
    @BindView(R.id.x_distance_et)
    EditText xD;
    @BindView(R.id.x_speed_et)
    EditText xS;
    @BindView(R.id.y_distance_et)
    EditText yD;
    @BindView(R.id.y_speed_et)
    EditText yS;
    @BindView(R.id.z_distance_et)
    EditText zD;
    @BindView(R.id.z_speed_et)
    EditText zS;
    @BindView(R.id.x_direction)
    CheckBox xDirection;
    @BindView(R.id.y_direction)
    CheckBox yDirection;
    @BindView(R.id.z_direction)
    CheckBox zDirection;
    private SerialPortHelper serialPortHelper = new SerialPortHelper(new SerialPortDevice(AppConfig.SERIAL_PORT, AppConfig.SERIAL_BAUD_RATE));
    private ExecutorService singlePool = Executors.newSingleThreadExecutor();
    @Override
    protected int layoutResId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        serialPortHelper.close();
    }

    /**
     * 电机（位置）初始化
     *
     * @param view
     */
    public void initPosition(View view) {
        singlePool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    serialPortHelper.open();
                    Bundle bundle = serialPortHelper.execute(Cmd.naInit(0x01));

                    if (bundle.getBoolean("suc")) {
                        byte[] data = bundle.getByteArray("data");
                        if (Cmd.cmdValidate(data)) {
                            ToastUtils.get().showText("电机（位置）初始化成功");
                            return;
                        }
                    }
                } catch (InterruptedException | IOException e) {
                    e.printStackTrace();
                } finally {
                    serialPortHelper.close();
                }
                ToastUtils.get().showText("电机（位置）初始化失败");
            }
        });
    }

    public void testX(View view) {
        singlePool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    serialPortHelper.open();
                    int distance = Integer.valueOf(xD.getText().toString());
                    int speed = Integer.valueOf(xS.getText().toString());
                    Bundle bundle = serialPortHelper.execute(Cmd.testX(0x01, xDirection.isChecked() ? 1 : 0, distance, speed));

                    if (bundle.getBoolean("suc")) {
                        byte[] data = bundle.getByteArray("data");
                        if (Cmd.cmdValidate(data)) {
                            ToastUtils.get().showText("水平动作测试成功");
                            return;
                        }
                    }
                } catch (InterruptedException | IOException e) {
                    e.printStackTrace();
                } finally {
                    serialPortHelper.close();
                }
                ToastUtils.get().showText("水平动作测试失败");
            }
        });
    }

    public void texY(View view) {

        singlePool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    serialPortHelper.open();
                    int distance = Integer.valueOf(yD.getText().toString());
                    int speed = Integer.valueOf(yS.getText().toString());
                    Bundle bundle = serialPortHelper.execute(Cmd.texY(0x01, yDirection.isChecked() ? 1 : 0, distance, speed));

                    if (bundle.getBoolean("suc")) {
                        byte[] data = bundle.getByteArray("data");
                        if (Cmd.cmdValidate(data)) {
                            ToastUtils.get().showText("垂直动作测试成功");
                            return;
                        }
                    }
                } catch (InterruptedException | IOException e) {
                    e.printStackTrace();
                } finally {
                    serialPortHelper.close();
                }
                ToastUtils.get().showText("垂直动作测试成功");
            }
        });
    }

    public void testZ(View view) {
        singlePool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    serialPortHelper.open();
                    int distance = Integer.valueOf(zD.getText().toString());
                    int speed = Integer.valueOf(zS.getText().toString());
                    Bundle bundle = serialPortHelper.execute(Cmd.testZ(0x01, zDirection.isChecked() ? 1 : 0, distance, speed));

                    if (bundle.getBoolean("suc")) {
                        byte[] data = bundle.getByteArray("data");
                        if (Cmd.cmdValidate(data)) {
                            ToastUtils.get().showText("内部垂直动作测试成功");
                            return;
                        }
                    }
                } catch (InterruptedException | IOException e) {
                    e.printStackTrace();
                } finally {
                    serialPortHelper.close();
                }
                ToastUtils.get().showText("内部垂直动作测试失败");
            }
        });

    }

    public void controlLed(View view) {
        singlePool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    serialPortHelper.open();
                    AppCompatButton button = (AppCompatButton) view;
                    String s = button.getText().toString();
                    int value = s.equals("LED开启") ? 0 : 1;
                    Bundle bundle = serialPortHelper.execute(Cmd.controlLed(0x01, value));
                    //帧头(0xA5 0x5A) + 设备地址 + 帧长(2byte) + 帧类型(0x01) + 上一控制帧命令码(1byte) + 异常码 + 校验
                    if (bundle.getBoolean("suc")) {
                        byte[] data = bundle.getByteArray("data");
                        if (Cmd.cmdValidate(data)) {
                            button.setText(s.equals("LED开启") ? "LED关闭" : "LED开启");
                            return;
                        }
                    }
                } catch (InterruptedException | IOException e) {
                    e.printStackTrace();
                } finally {
                    serialPortHelper.close();
                }
                ToastUtils.get().showText("LED设置失败");
            }
        });
    }

    public void controlFan(View view) {
        singlePool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    serialPortHelper.open();
                    AppCompatButton button = (AppCompatButton) view;
                    String s = button.getText().toString();
                    int value = s.equals("风扇开启") ? 0 : 1;
                    Bundle bundle = serialPortHelper.execute(Cmd.controlFan(0x01, value));
                    //帧头(0xA5 0x5A) + 设备地址 + 帧长(2byte) + 帧类型(0x01) + 上一控制帧命令码(1byte) + 异常码 + 校验
                    if (bundle.getBoolean("suc")) {
                        byte[] data = bundle.getByteArray("data");
                        if (Cmd.cmdValidate(data) && data[7] == 0) {
                            button.setText(s.equals("风扇开启") ? "风扇关闭" : "风扇开启");
                            return;
                        }
                    }
                } catch (InterruptedException | IOException e) {
                    e.printStackTrace();
                } finally {
                    serialPortHelper.close();
                }
                ToastUtils.get().showText("风扇设置失败");
            }
        });
    }

    public void controlUV(View view) {
        singlePool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    serialPortHelper.open();
                    AppCompatButton button = (AppCompatButton) view;
                    String s = button.getText().toString();
                    int value = s.equals("UV开启") ? 0 : 1;
                    Bundle bundle = serialPortHelper.execute(Cmd.controlUV(0x01, value));
                    //帧头(0xA5 0x5A) + 设备地址 + 帧长(2byte) + 帧类型(0x01) + 上一控制帧命令码(1byte) + 异常码 + 校验
                    if (bundle.getBoolean("suc")) {
                        byte[] data = bundle.getByteArray("data");
                        if (Cmd.cmdValidate(data) && data[7] == 0) {
                            button.setText(s.equals("UV开启") ? "UV关闭" : "UV开启");
                            return;
                        }
                    }
                } catch (InterruptedException | IOException e) {
                    e.printStackTrace();
                } finally {
                    serialPortHelper.close();
                }
                ToastUtils.get().showText("UV设置失败");
            }
        });

    }

    public void queryDoor(View view) {
        singlePool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    serialPortHelper.open();
                    Bundle bundle = serialPortHelper.execute(Cmd.queryDoor(0x01));
                    //`A5 5A``01``00 07``03``33``XX``XX`
                    if (bundle.getBoolean("suc")) {
                        byte[] data = bundle.getByteArray("data");
                        if (Cmd.cmdValidate(data)) {
                            ToastUtils.get().showText("舱门" + ((data[7] == 0) ? "未关闭" : "已关闭"));
                            return;
                        }
                    }
                } catch (InterruptedException | IOException e) {
                    e.printStackTrace();
                } finally {
                    serialPortHelper.close();
                }
                ToastUtils.get().showText("查询舱门是否完全关闭失败");
            }
        });

    }

    public void controlTemp(View view) {
        Intent intent = new Intent(this, TestTempActivity.class);
        startActivity(intent);
    }
}
